import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/loading_dialog.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/work_history.dart';

class WorkHistoryDetailView extends StatefulWidget {
  final String id;

  const WorkHistoryDetailView({Key key, this.id}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return WorkHistoryDetailViewState();
  }
}

class WorkHistoryDetailViewState extends State<WorkHistoryDetailView> {
  WorkHistory workHistory;
  Future loadFuture;
  bool isEdit;
  LoadingDialog loading;
  var format = new DateFormat('yyyy-MM-dd');

  @override
  void initState() {
    loading = new LoadingDialog(context);
    isEdit = widget.id != null && widget.id.isNotEmpty;
    loadFuture = loadWorkHistory();
    super.initState();
  }

  Future loadWorkHistory() async {
    if (isEdit) {
      var res = await Http.instance.post('/usercenter-app/workhistory/info/${widget.id}');
      if (res.code == 200) {
        workHistory = WorkHistory.fromJson(res.data);
      }
    } else {
      workHistory = new WorkHistory(userId: Auth.instance.userId);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('工作经历'),
        actions: [
          FlatButton(
            child: Text('保存'),
            onPressed: save,
          ),
        ],
      ),
      body: FutureBuilder(
        future: loadFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }

          return LoadingWidget();
        },
      ),
    );
  }

  Widget body() {
    return ListView(
      children: [
        fieldItem(
          field: leading('开始时间'),
          value: startTimeText,
        ),
        fieldItem(
          field: leading('结束时间'),
          value: endTimeText,
        ),
        fieldItem(
          field: leading('单位名称'),
          value: textField(
            workHistory.place,
            (val) => workHistory.place = val,
          ),
        ),
        fieldItem(
          field: leading('工作职务'),
          value: textField(
            workHistory.craft,
            (val) => workHistory.craft = val,
            lines: 3,
          ),
        ),
      ],
    );
  }

  Widget get startTimeText {
    return InkWell(
      child: title(formatDate(workHistory.startTime)),
      onTap: () async {
        var date = await getDate();
        if (date != null) {
          setState(() {
            workHistory.startTime = date;
          });
        }
      },
    );
  }

  String formatDate(DateTime dateTime) {
    if (dateTime == null) {
      return '请选择日期';
    }
    return format.format(dateTime);
  }

  Widget get endTimeText {
    return InkWell(
      child: title(formatDate(workHistory.endTime)),
      onTap: () async {
        var date = await getDate();
        if (date != null) {
          setState(() {
            workHistory.endTime = date;
          });
        }
      },
    );
  }

  Widget fieldItem({Widget field, Widget value}) {
    return Container(
      constraints: BoxConstraints(minHeight: 50),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.black12, width: 0.5),
        ),
      ),
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Padding(
            padding: EdgeInsets.only(right: 15),
            child: field,
          ),
          Expanded(child: value),
        ],
      ),
    );
  }

  Future<DateTime> getDate() async {
    return await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime.parse('1990-01-01'),
      lastDate: DateTime.now(),
    );
  }

  Widget leading(String text) {
    return Text(
      text,
      style: TextStyle(
        fontSize: 14,
        color: Colors.black54,
      ),
    );
  }

  Widget title(String text) {
    return Text(
      text,
      style: TextStyle(
        color: Colors.black,
        fontSize: 14,
      ),
    );
  }

  Widget textField(String value, Function(String) onChange, {int lines = 1}) {
    return TextField(
      onChanged: onChange,
      minLines: lines,
      maxLines: lines,
      style: TextStyle(fontSize: 14, color: Colors.black),
      controller: new TextEditingController(text: value ?? ''),
      decoration: InputDecoration(border: InputBorder.none),
    );
  }

  Future  save() async {
    String url;
    if (isEdit) {
      url = '/usercenter-app/workhistory/update';
    } else {
      url = '/usercenter-app/workhistory/save';
    }

    loading.show(text: '保存中');
    var res = await Http.instance.post(url, params: workHistory.toJson());
    loading.dismiss();
    if (res.code == 200) {
      Navigator.pop(context);
    } else {
      Fluttertoast.showToast(msg: res.msg); 
    }
  }
}
